package me.yushuai.wukong.base.api.util;

import me.yushuai.wukong.base.api.dto.PackingUomDTO;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;

/**
 * 包规单位工具类
 *
 * @author zhoushuai@189.cn
 * @since 2023-03-17
 */
public final class PackingUomUtil {

    private PackingUomUtil() {
    }

    /**
     * 用于把一个单位数据转换为另一个单位的数据，两个单位PackingId必须相同，如果两个单位所属包规Id不同不允许转换。
     *
     * @param qty         待转换的数量
     * @param originalUom 源单位
     * @param targetUom   目标单位
     * @return 转换为目标单位的数量
     */
    public static BigDecimal transform(@NotNull BigDecimal qty, @NotNull PackingUomDTO originalUom,
                                       @NotNull PackingUomDTO targetUom) {

        //1. 检查源单位与目标单位所属的包规是否相同
        final Long originalUomPackingId = originalUom.getPackingId();
        final Long targetUomPackingId = targetUom.getPackingId();
        if (!Objects.equals(originalUomPackingId, targetUomPackingId)) {
            throw new IllegalArgumentException("this packingId for originalUom and targetUom must be is same.");
        }

        //2. 检查源单位与目标单位中转换数量是否为空
        final BigDecimal originalUomQty = originalUom.getQty();
        final BigDecimal targetUomQty = targetUom.getQty();
        if (Objects.isNull(originalUomQty)) {
            throw new NullPointerException("originalUom.qty must be not null.");
        }

        if (Objects.isNull(targetUomQty)) {
            throw new NullPointerException("targetUom.qty must be not null.");
        }

        //3. 执行数据转换
        BigDecimal result = qty.multiply(originalUomQty);
        return result.divide(targetUomQty, RoundingMode.DOWN);
    }

    public static BigDecimal transformToEA(@NotNull BigDecimal qty, @NotNull PackingUomDTO packingUom) {
        final BigDecimal packingUomQty = packingUom.getQty();
        if (Objects.isNull(packingUomQty)) {
            throw new NullPointerException("packingUom.qty must be not null.");
        }
        return qty.multiply(packingUomQty);
    }
}
